package com.itzyf.pokemondata.activity.panel

import android.Manifest
import android.content.Intent
import android.net.Uri
import android.os.AsyncTask
import android.os.Environment
import android.text.InputType
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import com.bumptech.glide.Glide
import com.itzyf.pokemondata.R
import com.itzyf.pokemondata.bean.DbExclusive
import com.itzyf.pokemondata.bean.DbPokemon
import com.itzyf.pokemondata.bean.PokemonDo
import com.itzyf.pokemondata.fragment.ImageFragment
import com.itzyf.pokemondata.fragment.PayFragment
import com.itzyf.pokemondata.utils.FileUtil
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.tydic.baselibrary.activity.BaseActivity
import com.tydic.baselibrary.contant.Constant
import kotlinx.android.synthetic.main.activity_panel_detail.*
import kotlinx.android.synthetic.main.activity_realm.*
import kotlinx.android.synthetic.main.item_main.view.*
import org.litepal.LitePal
import java.io.File


/**
 * @author 依风听雨
 * @version 创建时间：2018/12/26 08:58
 */
class PanelDetailActivity : BaseActivity() {

    private lateinit var pokemonDo: PokemonDo
    private val pageList = mutableListOf<ImageFragment>()
    private val imgList = mutableListOf<String>()

    /**
     * 专属数据
     */
    private var exclusiveList: List<String>? = null

    override fun handlerActivity() {
        //初始值
        pokemonDo = PokemonDo()
        updatePanel()

        if (intent.getStringExtra("objId").isNullOrEmpty()) {
            val panel = intent.getIntArrayExtra("panel")
            pokemonDo.hp = panel[0]
            pokemonDo.pa = panel[1]
            pokemonDo.pd = panel[2]
            pokemonDo.sa = panel[3]
            pokemonDo.sd = panel[4]
            pokemonDo.speed = panel[5]

            pokemonDo.skin = intent.getStringExtra("skin")
            pokemonDo.specialTraining = intent.getStringExtra("specialTraining")
            pokemonDo.red1 = intent.getStringExtra("red1")
            pokemonDo.st2 = intent.getStringExtra("st2")
            setTitle(intent.getStringExtra("title"))

            prodValue.text = "无"
            prodValue.setOnClickListener {
                showProp()
            }
            ivStar.visibility = View.GONE
        } else {
            val dbPokemon = LitePal.where("objectId = ?", intent.getStringExtra("objId"))
                .findFirst(DbPokemon::class.java)
            if (dbPokemon == null) {
                showToast("获取面板数据异常")
                return
            }
            pokemonDo.hp = dbPokemon.hp
            pokemonDo.pa = dbPokemon.pa
            pokemonDo.pd = dbPokemon.pd
            pokemonDo.sa = dbPokemon.sa
            pokemonDo.sd = dbPokemon.sd
            pokemonDo.speed = dbPokemon.speed
            pokemonDo.skin = dbPokemon.skin
            pokemonDo.specialTraining = dbPokemon.specialTraining
            pokemonDo.red1 = dbPokemon.red1
            pokemonDo.isStar = dbPokemon.isStar
            pokemonDo.img = dbPokemon.img
            pokemonDo.st2 = dbPokemon.st2
            pokemonDo.skinImg = dbPokemon.skinImg

            if (pokemonDo.img.isNotEmpty()) {
                pageList.add(ImageFragment.newInstance(pokemonDo.img))
                imgList.add(pokemonDo.img)
            }
            if (pokemonDo.skinImg.isNotEmpty()) {
                val imgs = pokemonDo.skinImg.split(",")
                imgs.forEach {
                    pageList.add(ImageFragment.newInstance(it))
                    imgList.add(it)
                }
            }
            if (pageList.size > 0) {
                vpContent.visibility = View.VISIBLE
                vpContent.adapter = ImagePageAdapter(supportFragmentManager)
            }
            if (!TextUtils.isEmpty(dbPokemon.exclusiveId)) {
                val dbExclusive =
                    LitePal.where("objectId = ?", dbPokemon.exclusiveId)
                        .findFirst(DbExclusive::class.java)
                dbExclusive?.let {
                    exclusiveList =
                        listOf(it.name, "${it.hp},${it.pa},${it.pd},${it.sa},${it.sd},${it.speed}")
                }
            }

            //活力特性处理
            if (dbPokemon.pokemonName.contains(Regex("大力鳄|火精灵|艾比郎|波克基斯|血翼飞龙|捣蛋小锯鳄"))) {
                llHustle.visibility = View.VISIBLE
                llHustleLine.visibility = View.VISIBLE
                cbHustle.setOnCheckedChangeListener { _, isChecked ->
                    pokemonDo.isHustle(isChecked)
                    updatePanel()
                }
            }

            if (dbPokemon.pokemonName == "达摩狒狒-迦勒尔") {
                llTactics.visibility = View.VISIBLE
                llTacticsLine.visibility = View.VISIBLE
                cbTactics.setOnCheckedChangeListener { _, isChecked ->
                    pokemonDo.isTactics(isChecked)
                    updatePanel()
                }
            }

            if (dbPokemon.pokemonName.contains("无极极巨")) {
                pokemonDo.isBig = true
            }

            if (!dbPokemon.pokemonName.contains("专属")) {
                prodValue.text = "无"
                prodValue.setOnClickListener {
                    showProp()
                }
            } else {
                llProp.visibility = View.GONE
                llPropLine.visibility = View.GONE
            }

            if (dbPokemon.pokemonName.contains("未mega")) {
                pokemonDo.isMega = false
                tvStValue.text = "5"
                subtractEnable(false)
                addEnable(false)
            }


            setTitle(dbPokemon.pokemonName)
            ivStar.setImageResource(if (pokemonDo.isStar) R.drawable.ic_star_black_24dp else R.drawable.ic_star_border_black_24dp)
            ivStar.setOnClickListener {
                pokemonDo.isStar = !pokemonDo.isStar
                dbPokemon.isStar = pokemonDo.isStar
                dbPokemon.save()
                ivStar.setImageResource(if (pokemonDo.isStar) R.drawable.ic_star_black_24dp else R.drawable.ic_star_border_black_24dp)
            }
        }


//        if (pokemonDo.specialTraining == null) {
////            cbSpecialTraining.isChecked = true
////            cbSpecialTraining.isEnabled = false
//            subtractEnable(false)
//            addEnable(false)
//        }


        if (pokemonDo.red1.isEmpty()) {
            cbRed1.isChecked = false
            cbRed1.isEnabled = false
        }

        pokemonDo.finisInit()


        //默认关闭特训
        pokemonDo.setSpecialTrainingIndex(0)
        updatePanel()


        if (pokemonDo.isSkin()) {
            llSkin.visibility = View.VISIBLE
            vSkin.visibility = View.VISIBLE
        }

        //努力值
        effortValue.text = "无"
        effortValue.setOnClickListener {
            showEffortDialog()
        }

        cbContract.setOnCheckedChangeListener { _, isChecked ->
            pokemonDo.contract(if (isChecked) 800 else 0)
            updatePanel()
        }

        //性格
        characterValue.text = "平衡"
        characterValue.setOnClickListener { showCharacterDialog() }

        //亲密度
        cbIntimacy.setOnCheckedChangeListener { _, isChecked ->
            pokemonDo.intimacy(isChecked)
            updatePanel()
        }
        //皮肤
        cbSkin.setOnCheckedChangeListener { _, isChecked ->
            pokemonDo.skin(isChecked)
            updatePanel()
            showImg()
        }

        //特训
//        cbSpecialTraining.setOnCheckedChangeListener { _, isChecked ->
//            pokemonDo.isSpecialTraining(isChecked)
//            updatePanel()
//        }
        if (!pokemonDo.specialTraining.isNullOrBlank()) {
            tvStValue.text = "0"
            subtractEnable(false)
            addEnable(true)

            val max = if (pokemonDo.st2.isNullOrBlank()) 1 else 2

            subtract.setOnClickListener {
                addEnable(true)
                var current = tvStValue.text.toString().toInt()
                current--
                tvStValue.text = current.toString()
                pokemonDo.setSpecialTrainingIndex(current)
                updatePanel()
                if (current <= 0) {
                    subtractEnable(false)
                }
            }

            add.setOnClickListener {
                subtractEnable(true)
                var current = tvStValue.text.toString().toInt()
                current++
                tvStValue.text = current.toString()
                pokemonDo.setSpecialTrainingIndex(current)
                updatePanel()
                if (current >= max) {
                    addEnable(false)
                }
            }
        }


        cbRed1.setOnCheckedChangeListener { _, isChecked ->
            pokemonDo.isRed1(isChecked)
            updatePanel()
        }
        val guildAttackValue = sp.getString("guildAttackValue", "0%")
        val guildDefenseValue = sp.getString("guildDefenseValue", "0%")
        tvGuildValue.text = "攻：$guildAttackValue；防：$guildDefenseValue"
        cbGuild.setOnCheckedChangeListener { _, isChecked ->

            val a = guildAttackValue!!.replace("%", "").toInt() * 0.01
            val b = guildDefenseValue!!.replace("%", "").toInt() * 0.01
            if (isChecked) {
                pokemonDo.guild(a, b)
            } else {
                pokemonDo.guild(0.0, 0.0)
            }
            updatePanel()
        }
    }

    private fun showImg() {
        if (cbSkin.isChecked && pokemonDo.skinImg.isNotEmpty()) {
            vpContent.currentItem = pageList.size - 1
        } else if (pokemonDo.img.isNotEmpty()) {
            vpContent.currentItem = 0
        }
    }

    inner class ImagePageAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm) {
        override fun getItem(position: Int) = pageList[position]

        override fun getCount() = pageList.size

    }


    private fun subtractEnable(enable: Boolean) {
        if (enable) {
            subtract.setImageDrawable(resources.getDrawable(R.drawable.ic_remove_black_24dp))
            subtract.isEnabled = true
        } else {
            subtract.setImageDrawable(resources.getDrawable(R.drawable.ic_remove_gray_24dp))
            subtract.isEnabled = false
        }
    }

    private fun addEnable(enable: Boolean) {
        if (enable) {
            add.setImageDrawable(resources.getDrawable(R.drawable.ic_add_black2_24dp))
            add.isEnabled = true
        } else {
            add.setImageDrawable(resources.getDrawable(R.drawable.ic_add_black3_24dp))
            add.isEnabled = false
        }
    }

    /**
     * 性格
     */
    private fun showCharacterDialog() {
        val character = arrayOf(
            "开朗（速度↑;特攻↓）",
            "胆小（速度↑;物攻↓）",
            "固执（物攻↑;特攻↓）",
            "保守（特攻↑;物攻↓）",

            "大胆（物防↑;物攻↓）",
            "淘气（物防↑;特攻↓）",
            "沉着（特防↑;物攻↓）",
            "慎重（特防↑;特攻↓）",

            "孤独（物攻↑;物防↓）",
            "调皮（物攻↑;特防↓）",
            "勇敢（物攻↑;速度↓）",

            "稳重（特攻↑;物防↓）",
            "马虎（特攻↑;特防↓）",
            "冷静（特攻↑;速度↓）",

            "急躁（速度↑;物防↓）",
            "天真（速度↑;特防↓）",

            "乐天（物防↑;特防↓）",
            "悠闲（物防↑;速度↓）",

            "温顺（特防↑;物防↓）",
            "狂妄（特防↑;速度↓）",

            "平衡"
        )

        val builder = QMUIDialog.CheckableDialogBuilder(this)
            .addItems(character) { dialog, which ->
                when (which) {
                    0 -> character(PokemonDo.SPEED, PokemonDo.SA)//开朗
                    1 -> character(PokemonDo.SPEED, PokemonDo.PA)//胆小
                    2 -> character(PokemonDo.PA, PokemonDo.SA)//固执
                    3 -> character(PokemonDo.SA, PokemonDo.PA)//保守

                    4 -> character(PokemonDo.PD, PokemonDo.PA)//大胆
                    5 -> character(PokemonDo.PD, PokemonDo.SA)//淘气
                    6 -> character(PokemonDo.SD, PokemonDo.PA)//沉着
                    7 -> character(PokemonDo.SD, PokemonDo.SA)//慎重

                    8 -> character(PokemonDo.PA, PokemonDo.PD)//孤独
                    9 -> character(PokemonDo.PA, PokemonDo.SD)//调皮
                    10 -> character(PokemonDo.PA, PokemonDo.SPEED)//勇敢

                    11 -> character(PokemonDo.SA, PokemonDo.PD)//稳重
                    12 -> character(PokemonDo.SA, PokemonDo.SD)//马虎
                    13 -> character(PokemonDo.SA, PokemonDo.SPEED)//冷静

                    14 -> character(PokemonDo.SPEED, PokemonDo.PD)//急躁
                    15 -> character(PokemonDo.SPEED, PokemonDo.SD)//天真

                    16 -> character(PokemonDo.PD, PokemonDo.SD)//乐天
                    17 -> character(PokemonDo.PD, PokemonDo.SPEED)//悠闲

                    18 -> character(PokemonDo.SD, PokemonDo.PD)//温顺
                    19 -> character(PokemonDo.SD, PokemonDo.SPEED)//狂妄

                    20 -> character(0, 0)//"平衡
                }
                characterValue.text =
                    character[which]
                dialog.dismiss()
            }
        builder.show()
    }

    private fun character(characterRise: Int, characterDecline: Int) {
        pokemonDo.character(characterRise, characterDecline)
        updatePanel()
    }

    /**
     * 努力值加成
     */
    private fun showEffortDialog() {
        val dimension = resources.getStringArray(R.array.dimension)
        val builder = QMUIDialog.MultiCheckableDialogBuilder(this)
            .setCheckedItems(1)
            .addItems(dimension) { _, _ -> }
        builder.addAction("取消") { dialog, _ -> dialog.dismiss() }
        builder.addAction("提交") { dialog, _ ->
            if (builder.checkedItemIndexes.size > 2) {
                showToast("最多只能选择两个")
                return@addAction
            }
            var result = ""
            var effort = 0
            for (i in builder.checkedItemIndexes.indices) {
                result += "" + dimension[builder.checkedItemIndexes[i]] + "; "
                effort = effort or getEffort(builder.checkedItemIndexes[i])
            }
            pokemonDo.effort(effort)
            updatePanel()
            effortValue.text = if (TextUtils.isEmpty(result)) "无" else result
            dialog.dismiss()
        }
        builder.show()
    }

    fun getEffort(index: Int): Int {
        var effort = 0
        when (index) {
            0 -> effort = PokemonDo.HP
            1 -> effort = PokemonDo.PA
            2 -> effort = PokemonDo.PD
            3 -> effort = PokemonDo.SA
            4 -> effort = PokemonDo.SD
            5 -> effort = PokemonDo.SPEED
        }
        return effort
    }

    /**
     * 道具加成面板
     */
    private fun showProp() {
        val propMap = mutableMapOf(
            "无" to "0,0,0,0,0,0",
            "狗粮" to "15,0,0,0,0,0",
            "好人卡" to "0,0,15,0,0,0",
            "精密装甲" to "0,0,0,0,10,0",
            "限定头巾" to "0,50,0,0,0,0",
            "限定眼镜" to "0,0,0,50,0,0",
            "限定围巾" to "0,0,0,0,0,50",
            "突击装甲/棉被" to "0,0,50,0,0,0",
            "突击背心" to "0,0,0,0,50,0",
            "道具魔术胶" to "0,0,8,0,0,0",
            "贺岁限定头巾" to "0,55,0,0,0,0",
            "金猪限定眼镜" to "0,0,0,55,0,0",
            "金猪限定围巾" to "0,0,0,0,0,55",
            "血量健身环" to "0,0,0,0,0,0,-1,0,0,0,0,0",
            "物攻健身环" to "0,0,0,0,0,0,0,-1,0,0,0,0",
            "物防健身环" to "0,0,0,0,0,0,0,0,-1,0,0,0",
            "特攻健身环" to "0,0,0,0,0,0,0,0,0,-1,0,0",
            "特防健身环" to "0,0,0,0,0,0,0,0,0,0,-1,0"
        )
        if (exclusiveList != null && exclusiveList!!.size == 2) {
            propMap[exclusiveList!![0]] = exclusiveList!![1]
        }
        val propName: MutableList<String> = ArrayList()

        for ((key, value) in propMap) {//迭代 map，把 key 和 value 赋值给变量
            propName.add(key)
        }

        val builder = QMUIDialog.CheckableDialogBuilder(this)
            .addItems(propName.toTypedArray()) { dialog, which ->
                //道具加成
                pokemonDo.propAddition(propMap[propName[which]]!!)
                prodValue.text = propName[which]
                updatePanel()
                dialog.dismiss()
            }
        builder.show()
    }

    override fun getContentViewId() = R.layout.activity_panel_detail

    override fun getToolbarTitle() = ""


    /**
     * 更新面板数据
     */
    private fun updatePanel() {
        progressHp.progress = pokemonDo.hp.toFloat()
        progressPa.progress = pokemonDo.pa.toFloat()
        progressPd.progress = pokemonDo.pd.toFloat()
        progressSa.progress = pokemonDo.sa.toFloat()
        progressSd.progress = pokemonDo.sd.toFloat()
        progressSpeed.progress = pokemonDo.speed.toFloat()


        tvHp.text = "${pokemonDo.hp}"
        tvPa.text = "${pokemonDo.pa}"
        tvPd.text = "${pokemonDo.pd}"
        tvSa.text = "${pokemonDo.sa}"
        tvSd.text = "${pokemonDo.sd}"
        tvSpeed.text = "${pokemonDo.speed}"
    }


    fun saveImage() {
        if (hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            doSDCardPermission()
        } else {
            requestPermission(
                Constant.WRITE_READ_EXTERNAL_CODE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
        }
    }

    override fun doSDCardPermission() {
        download(imgList[vpContent.currentItem])
    }


    // 保存图片到手机
    private fun download(url: String) {

        object : AsyncTask<Void, Int, File>() {

            override fun doInBackground(vararg params: Void): File? {
                var file: File? = null
                try {
                    val future = Glide
                        .with(this@PanelDetailActivity)
                        .load(url)
                        .downloadOnly(
                            com.bumptech.glide.request.target.Target.SIZE_ORIGINAL,
                            com.bumptech.glide.request.target.Target.SIZE_ORIGINAL
                        )

                    file = future.get()

                    // 首先保存图片
                    val pictureFolder =
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).absoluteFile

                    val appDir = File(pictureFolder, "fuke")
                    if (!appDir.exists()) {
                        appDir.mkdirs()
                    }
                    val fileName = System.currentTimeMillis().toString() + ".jpg"
                    val destFile = File(appDir, fileName)

                    FileUtil.CopyFile(file, destFile)

                    // 最后通知图库更新
                    sendBroadcast(
                        Intent(
                            Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                            Uri.fromFile(File(destFile.getPath()))
                        )
                    )


                } catch (e: Exception) {
                    e.printStackTrace()
                }

                return file
            }

            override fun onPostExecute(file: File) {
                showToast("保存成功")
            }

        }.execute()
    }

}